package com.zx.mobile.controller;

import com.zx.exception.GlobalServiceException;
import com.zx.map.service.MerchantInfoService;
import com.zx.map.service.ShareProfitDetailLogService;
import com.zx.map.service.ShareProfitLogService;
import com.zx.map.service.model.*;
import com.zx.map.utils.SUConstants;
import com.zx.mobile.MobileCommonHelper;
import com.zx.mobile.SessionHelper;
import com.zx.mobile.domain.MobileUserDomain;
import com.zx.mobile.domain.ShareProfitDetailDaily;
import com.zx.mobile.domain.SpDetailDomain;
import com.zx.mobile.domain.TransferShareProfitDomain;
import com.zx.mobile.utils.WebUtils;
import com.zx.platform.utils.DateUtils;
import com.zx.platform.utils.MD5Util;
import com.zx.platform.utils.PmpUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by IntelliJ IDEA. User: Administrator Date: 15-7-5 Time: 下午8:09 To
 * change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/mobile/sprofit")
public class ShareProfitLogController {
    /**
     * log
     */
    private static Logger log = Logger.getLogger(ShareProfitLogController.class);
    @Autowired
    private ShareProfitLogService shareProfitLogService;
    @Autowired
    private MerchantInfoService merchantInfoService;
    @Autowired
    private ShareProfitDetailLogService shareProfitDetailLogService;


    /**
     * 分享收益首页
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/queryShareProfit")
    public String queryShareProfit(Model model, HttpServletRequest request) {
        try {
            // 获取session信息
            MobileUserDomain user = (MobileUserDomain) request.getSession()
                    .getAttribute(SessionHelper.MOBILEUSER);
            //获取最新数据
            MerchantInfoModel currentModel = merchantInfoService.getModelByKey(user.getMerchantInfoDetailModel().getMerchantId());
            //交易密码不为空的情况下  允许用户进行设置密码
            //若交易密码为空 需要用户先设置密码
            if (StringUtils.isNotBlank(currentModel.getTradePassword())) {
                ShareProfitLogModel temp = shareProfitLogService.queryProfitByCustSysAccount(user.getMerchantInfoDetailModel().getSysAccount());
                if (null == temp) {
                    temp = new ShareProfitLogModel();
                }
                model.addAttribute("temp", temp);
                return "/jsp/mobile/shareprofit/spindex";
            } else {
                model.addAttribute("operatorType", MobileCommonHelper.URLRETURN_SHAREPROFIT);//设置交易密码 回退到修改交易密码
                return "/jsp/mobile/pwd/setpaypwd";
            }

        } catch (Exception e) {
            model.addAttribute("errorMsg", "系统异常");
            log.error("系统异常", e);
            return "/jsp/mobile/error";
        }
    }

    /**
     * 分享收益转出
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/transferShareProfit")
    public String transferShareProfit(TransferShareProfitDomain transferShareProfitDomain,
                                      Model model, HttpServletRequest request) {
        try {
            log.debug("收益分享转出："
                    + ToStringBuilder.reflectionToString(transferShareProfitDomain));
            // 验证交易密码是否正确
            MerchantInfoDetailModel merchantInfoDetailModel=WebUtils.queryCurrentLoginMerchantInfoDetailModel(request);
            String tradePwd = PmpUtils.encoderByMD5(MD5Util
                    .getMD5Str(transferShareProfitDomain.getTradePwd()));
            //获取最新数据
            MerchantInfoModel curMerchantInfoModel = merchantInfoService.getMerchantInfoModelBySysAccount(merchantInfoDetailModel.getSysAccount());
            if (!tradePwd.equals(curMerchantInfoModel.getTradePassword())) {
                model.addAttribute("errorMsg", "交易密码错误");
                return "/jsp/mobile/error";
            } else {
                try {
                    shareProfitLogService.transferShareProfit(transferShareProfitDomain,curMerchantInfoModel);
                    model.addAttribute("transferShareProfitDomain", transferShareProfitDomain);
                    return "/jsp/mobile/shareprofit/transfersuccess";
                } catch (GlobalServiceException e) {
                    log.error("分享收益转出出现异常", e);
                    model.addAttribute("errorMsg", e.getMessage());
                    return "/jsp/mobile/error";
                }
            }
        } catch (Exception e) {
            model.addAttribute("errorMsg", "系统异常");
            log.error("系统异常", e);
            return "/jsp/mobile/error";
        }
    }

    /**
     * 分享交易查询 查询自己受益详情
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/querySpTrade")
    public String querySpTrade(SpDetailDomain spDetailDomain, Model model, HttpServletRequest request) {
        try {
            // 获取session信息
            MerchantInfoDetailModel merchantInfoDetailModel=WebUtils.queryCurrentLoginMerchantInfoDetailModel(request);
            spDetailDomain.setSysAccount(merchantInfoDetailModel.getSysAccount());
            if (StringUtils.isBlank(spDetailDomain.getBeginDate())) {
                spDetailDomain.setBeginDate(PmpUtils.dateToString(
                        DateUtils.getMonthFirstDateOf(new Date()), "yyyy-MM-dd"));
            }
            if (StringUtils.isBlank(spDetailDomain.getEndDate())) {
                spDetailDomain.setEndDate(PmpUtils.dateToString(new Date(),
                        "yyyy-MM-dd"));
            }
            //ShareProfitDetailLogModel param = new ShareProfitDetailLogModel();
            // param.setAgentSysAccount(user.getMerchantInfoDetailModel().getSysAccount());
            List<ShareProfitDetailLogModel> list = shareProfitDetailLogService.getListByModel(spDetailDomain);
            BigDecimal totalAmt = new BigDecimal("0");
            //组装信息
            Map<String, ShareProfitDetailDaily> map = new HashMap<String, ShareProfitDetailDaily>();
            List<ShareProfitDetailDaily> listDaily = new ArrayList<ShareProfitDetailDaily>();
            for (ShareProfitDetailLogModel oo : list) {
                totalAmt = totalAmt.add(new BigDecimal(oo.getSpDetailAmt()));
                MerchantInfoModel temp = merchantInfoService.getModelByKey(oo.getMerchantId());
                oo.setMerchantName(temp.getMerchantName());
                if (map.containsKey(oo.getSpDetailDay())) {
                    // map中包含数据的 增加数据
                    ShareProfitDetailDaily shareProfitDetailDaily = map.get(oo.getSpDetailDay());
                    shareProfitDetailDaily.getSpList().add(oo);
                } else {
                    // map中不包含数据的 构造数据
                    ShareProfitDetailDaily shareProfitDetailDaily = new ShareProfitDetailDaily();
                    List<ShareProfitDetailLogModel> dateList = new ArrayList<ShareProfitDetailLogModel>();
                    shareProfitDetailDaily.setSpDate(oo.getSpDetailDay());
                    dateList.add(oo);
                    shareProfitDetailDaily.setSpList(dateList);
                    listDaily.add(shareProfitDetailDaily);
                    map.put(oo.getSpDetailDay(), shareProfitDetailDaily);
                }
            }
            //对数据进行排序
            Collections.sort(listDaily, new Comparator<ShareProfitDetailDaily>() {
                public int compare(ShareProfitDetailDaily o1, ShareProfitDetailDaily o2) {
                    return o2.getSpDate().compareTo(o1.getSpDate());
                }
            });
            model.addAttribute("list", listDaily);
            model.addAttribute("domain", spDetailDomain);
            model.addAttribute("totalAmt", totalAmt.doubleValue());
            return "/jsp/mobile/shareprofit/sptrade";
        } catch (Exception e) {
            model.addAttribute("errorMsg", "系统异常");
            log.error("系统异常", e);
            return "/jsp/mobile/error";
        }
    }

    /**
     * 分享用户查询
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/customer")
    public String customer(Model model, HttpServletRequest request) {
        try {
            // 获取session信息

            AgentInfoModel agent = WebUtils.queryCurrentLoginAgentInfo(request);
            List<MerchantInfoModel> list = new ArrayList<MerchantInfoModel>();
            MerchantInfoModel merchantInfoModel = new MerchantInfoModel();
            if (null != agent) {
                agent.setHasSelf(true);
                //意愿代理只查看自己的直属客户
                if(agent.getAgentLevel().equals(SUConstants.AGENT_LEVEL_WILL)){
                    merchantInfoModel.setAgentId(agent.getAgentId());
                }
                list = merchantInfoService.queryListMerchantInfoModelByAgentInfo(agent,merchantInfoModel);
            }
            model.addAttribute("list", list);
            return "/jsp/mobile/shareprofit/spcustomer";
        } catch (Exception e) {
            model.addAttribute("errorMsg", "系统异常");
            log.error("系统异常", e);
            return "/jsp/mobile/error";
        }
    }
}
